package foundation.huffuman_tree;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

/**
 * Huffuman树
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // 单调递减栈
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            int tmp = sc.nextInt();
            Deque<Integer> tmpDeque = new ArrayDeque<>(); // 单调递增栈
            while (!deque.isEmpty() && tmp > deque.peek()) {
                tmpDeque.push(deque.pop());
            }
            deque.push(tmp);
            while (!tmpDeque.isEmpty()) {
                deque.push(tmpDeque.pop());
            }
        }
        int res = 0;
        while (deque.size() > 1) {
            int tmp = deque.pop() + deque.pop();
            res += tmp;
            Deque<Integer> tmpDeque = new ArrayDeque<>(); // 单调递增栈
            while (!deque.isEmpty() && tmp > deque.peek()) {
                tmpDeque.push(deque.pop());
            }
            deque.push(tmp);
            while (!tmpDeque.isEmpty()) {
                deque.push(tmpDeque.pop());
            }
        }
        System.out.println(res);
    }
}
